package com.example.springstudyroot.proxy.jdk;

import com.example.springstudyroot.proxy.UserService;
import com.sun.org.apache.bcel.internal.util.ClassLoader;
import jdk.internal.org.objectweb.asm.ClassWriter;
import jdk.internal.org.objectweb.asm.MethodVisitor;
import jdk.internal.org.objectweb.asm.Opcodes;

import java.io.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JdkProxyTest {
    public static void main(String[] args) throws IOException {
        ClassWriter classWriter = new ClassWriter(0);

        //通过visit方法确定类的头部信息
        classWriter.visit(Opcodes.V1_8,//java版本
                Opcodes.ACC_PUBLIC,//类修饰符
                "Person",//类的全限定名
                null,
                "java.lang.Object",//父类包路径名
                null);

        //创建构造函数
        MethodVisitor mv = classWriter.visitMethod(Opcodes.ACC_PUBLIC,//方法修饰符
                "<init>",//构造方法
                 "()V",//方法返回值
                 null,null );
        mv.visitCode();
        mv.visitVarInsn(Opcodes.ALOAD,0);
        mv.visitMethodInsn(Opcodes.INVOKESPECIAL,"java/lang/Object","<init>", "()V");
        mv.visitInsn(Opcodes.RETURN);
        mv.visitMaxs(1,1);
        mv.visitEnd();

        //定义test方法
        MethodVisitor methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC, "test", "()V", null, null);
        methodVisitor.visitCode();
        methodVisitor.visitFieldInsn(Opcodes.GETSTATIC,"java/lang/System", "out", "Ljava/io/PrintStream;");
        methodVisitor.visitLdcInsn("hello lihai");
        methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL,"java/io/PrintStream","println", "(Ljava/lang/String;)V");
        methodVisitor.visitInsn(Opcodes.RETURN);
        methodVisitor.visitMaxs(2,2);
        methodVisitor.visitEnd();
        //classWriter类已经完成
        classWriter.visitEnd();

        //将classwriter转换为字节数组写入文件
        byte[] data = classWriter.toByteArray();
        File file = new File("D:\\javaRepository\\myCode\\study\\springstudyroot\\target\\classes\\com\\example\\springstudyroot\\proxy\\Person.class");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(data);
        fileOutputStream.close();


    }

}
